# Differentiable Augmentation for Data-Efficient GAN Training
# Shengyu Zhao, Zhijian Liu, Ji Lin, Jun-Yan Zhu, and Song Han
# https://arxiv.org/pdf/2006.10738
# https://github.com/mit-han-lab/data-efficient-gans/blob/master/DiffAugment_pytorch.py

import torch
import torch.nn.functional as F
from random import random
import kornia as K
from math import pi, cos


class DiffAug(torch.nn.Module):
    def __init__(self, total_iter, p = 0.6) -> None:
        super().__init__()
        self.total_iter = total_iter
        self.count = 0.
        self.p = p
        self.this_p = 0.
        self.update_interval = 4
        self.t = 0.6
        self.da_interval = 1e-4
    
    def forward(self, x):
        p = self.this_p
        return DiffAugment(x, 'color', prob=p)
        
    def step(self, out_real):
        self.count += 1
        if self.count % self.update_interval == 0:
            adjust = torch.sign(out_real - self.t).mean() * self.da_interval
            self.this_p += adjust.item()
            self.this_p = min( max(self.this_p, 0), self.p )
    
    def step_fake(self, out_fake):
        self.count += 1
        if self.count % self.update_interval == 0:
            adjust = torch.sign(- out_fake - self.t).mean() * self.da_interval
            # self.this_p.add_(adjust).clamp_( 0. , self.p )
            self.this_p += adjust.item()
            self.this_p = min( max(self.this_p, 0), self.p )

def DiffAugment(x, policy='color,translation,cutout', channels_first=True, prob=0.):
    if policy and prob > 0.:
        if not channels_first:
            x = x.permute(0, 3, 1, 2)
        for p in policy.split(','):
            for f in AUGMENT_FNS[p]:
                x = f(x, prob)
        if not channels_first:
            x = x.permute(0, 2, 3, 1)
        x = x.contiguous()
    return x


def rand_hue(x):
    x = K.enhance.denormalize(x, torch.tensor(0.5), torch.tensor(0.5))
    x = K.enhance.adjust_hue(x, (random()-0.5)*0.1*pi)
    x = K.enhance.normalize(x, torch.tensor(0.5), torch.tensor(0.5))
    return x

def rand_sharpness(x, p):
    return x if p < 1e-2 else K.enhance.sharpness(x, 0.2 * p)

def rand_blur(x):
    kernel_size = (3, ) * 2
    sigma = (1 + random() * 0.5, ) * 2
    return K.filters.gaussian_blur2d(x, kernel_size, sigma, border_type='reflect')

def rand_brightness(x, p):
    x = x + (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5) * p
    return x


def rand_saturation(x, p):
    x_mean = x.mean(dim=1, keepdim=True)
    x = (x - x_mean) * ((torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5 ) * p * 2 + 1) + x_mean
    return x


def rand_contrast(x, p):
    x_mean = x.mean(dim=[1, 2, 3], keepdim=True)
    x = (x - x_mean) * ((torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5) * p + 1) + x_mean
    return x


def rand_translation(x, p, ratio=0.1):
    ratio *= p
    shift_x, shift_y = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5)
    if shift_x == 0 or shift_y == 0:
        return x
    translation_x = torch.randint(-shift_x, shift_x + 1, size=[x.size(0), 1, 1], device=x.device)
    translation_y = torch.randint(-shift_y, shift_y + 1, size=[x.size(0), 1, 1], device=x.device)
    grid_batch, grid_x, grid_y = torch.meshgrid(
        torch.arange(x.size(0), dtype=torch.long, device=x.device),
        torch.arange(x.size(2), dtype=torch.long, device=x.device),
        torch.arange(x.size(3), dtype=torch.long, device=x.device),
    )
    grid_x = torch.clamp(grid_x + translation_x + 1, 0, x.size(2) + 1)
    grid_y = torch.clamp(grid_y + translation_y + 1, 0, x.size(3) + 1)
    x_pad = F.pad(x, [1, 1, 1, 1, 0, 0, 0, 0])
    x = x_pad.permute(0, 2, 3, 1).contiguous()[grid_batch, grid_x, grid_y].permute(0, 3, 1, 2).contiguous()
    return x


def rand_cutout(x, p, ratio=0.1):
    ratio *= p
    cutout_size = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5)
    if cutout_size == 0:
        return x
    offset_x = torch.randint(0, x.size(2) + (1 - cutout_size[0] % 2), size=[x.size(0), 1, 1], device=x.device)
    offset_y = torch.randint(0, x.size(3) + (1 - cutout_size[1] % 2), size=[x.size(0), 1, 1], device=x.device)
    grid_batch, grid_x, grid_y = torch.meshgrid(
        torch.arange(x.size(0), dtype=torch.long, device=x.device),
        torch.arange(cutout_size[0], dtype=torch.long, device=x.device),
        torch.arange(cutout_size[1], dtype=torch.long, device=x.device),
    )
    grid_x = torch.clamp(grid_x + offset_x - cutout_size[0] // 2, min=0, max=x.size(2) - 1)
    grid_y = torch.clamp(grid_y + offset_y - cutout_size[1] // 2, min=0, max=x.size(3) - 1)
    mask = torch.ones(x.size(0), x.size(2), x.size(3), dtype=x.dtype, device=x.device)
    mask[grid_batch, grid_x, grid_y] = 0
    x = x * mask.unsqueeze(1)
    return x


AUGMENT_FNS = {
    'color': [rand_brightness, rand_saturation, rand_contrast],
    'translation': [rand_sharpness, rand_translation],
    'cutout': [rand_cutout, ]*3,
}